package com.example.leoss.zhuye;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.example.leoss.R;
import com.example.leoss.ViewPagerIndicator;
import com.example.leoss.duanxingxufa.MsgMobanActivity;
import com.example.leoss.img.GlideRectRound;
import com.example.leoss.onclick_tmds.MobanActivity;
import com.example.leoss.zhuye.File_xianshi.ToFileActivity;
import com.example.leoss.zhuye.LineChartActivity.MyMarkerView;
import com.example.leoss.zhuye.listviewitems.BarChartItem;
import com.example.leoss.zhuye.listviewitems.ChartItem;
import com.example.leoss.zhuye.listviewitems.LineChartItem;
import com.example.leoss.zhuye.listviewitems.MyListview;
import com.example.leoss.zhuye.listviewitems.PieChartItem;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IFillFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.Utils;

import java.util.ArrayList;
import java.util.List;

public class ShouyeFragment extends Fragment implements ViewPager.OnPageChangeListener, View.OnClickListener, SeekBar.OnSeekBarChangeListener,
        OnChartValueSelectedListener {
    private static ProgressDialog dialog;
    private ViewPager viewPager;
    private int[] imageResIds;
    private ArrayList<ImageView> imageViewList;
    static boolean isRunning = false;
    public View view;
    private ViewPagerIndicator mIndicatorCircleLine, mIndicatorSpring;
    public Context context = getActivity();
    private LineChart chart;

    public static ShouyeFragment newInstance(String info) {
        Bundle args = new Bundle();
        ShouyeFragment fragment = new ShouyeFragment();
        args.putString("info", info);
        fragment.setArguments(args);
        return fragment;
    }
    /**
     * 点击事件
     */
    ImageButton img_btn_tonxun, img_btn_dwlo, img_btn_daunxin, img_btn_jiaochen;


    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {


       // getActivity().getWindow().setTitle("首页");
        //该View表示该碎片的主界面,最后要返回该view
        view = inflater.inflate(R.layout.fragment_shouye, container, false);
        getActivity().getWindow().setTitle(getArguments().getString("info"));
        //找到主界面view后，就可以进行UI的操作了。
        //注意：因为主界面现在是view，所以在找寻控件时要用view.findViewById

        // 初始化布局 View视图
        initViews();

        // Model数据
        initData();

        viewPager.setAdapter(new MyAdapter());

        // 开启轮询
        new Thread() {
            public void run() {
                isRunning = true;
                while (isRunning) {
                    try {
                        Thread.sleep(4000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // 往下跳一位
                    getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
                        }
                    });
                }
            }

        }.start();

        onTubaio();

        return view;
    }

    @SuppressLint("ClickableViewAccessibility")
    private void onTubaio() {


        MyListview lv =view.findViewById(R.id.list1);

        lv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                Log.d("MainActivity","onTouch");
                return false;
            }
        });


        ArrayList<ChartItem> list = new ArrayList<>();




                list.add(new LineChartItem(generateDataLine( 1), getActivity().getApplicationContext()));

                list.add(new BarChartItem(generateDataBar( 1), getActivity().getApplicationContext()));

                list.add(new PieChartItem(generateDataPie(), getActivity().getApplicationContext()));



        ChartDataAdapter cda = new ChartDataAdapter(getActivity().getApplicationContext(), list);
        lv.setAdapter(cda);
    }

    /**
     * adapter that supports 3 different item types
     */
    private class ChartDataAdapter extends ArrayAdapter<ChartItem> {

        ChartDataAdapter(Context context, List<ChartItem> objects) {
            super(context, 0, objects);
        }

        @NonNull
        @Override
        public View getView(int position, View convertView, @NonNull ViewGroup parent) {
            //noinspection ConstantConditions
            return getItem(position).getView(position, convertView, getContext());
        }

        @Override
        public int getItemViewType(int position) {
            // return the views type
            ChartItem ci = getItem(position);
            return ci != null ? ci.getItemType() : 0;
        }

        @Override
        public int getViewTypeCount() {
            return 3; // we have 3 different item-types
        }
    }

    /**
     * generates a random ChartData object with just one DataSet
     *
     * @return Line data
     */
    private LineData generateDataLine(int cnt) {

        ArrayList<Entry> values1 = new ArrayList<>();

        for (int i = 0; i < 12; i++) {
            values1.add(new Entry(i, (int) (Math.random() * 65) + 40));
        }

        LineDataSet d1 = new LineDataSet(values1, "New DataSet " + cnt + ", (1)");
        d1.setLineWidth(2.5f);
        d1.setCircleRadius(4.5f);
        d1.setHighLightColor(Color.rgb(244, 117, 117));
        d1.setDrawValues(false);

        ArrayList<Entry> values2 = new ArrayList<>();

        for (int i = 0; i < 12; i++) {
            values2.add(new Entry(i, values1.get(i).getY() - 30));
        }

        LineDataSet d2 = new LineDataSet(values2, "New DataSet " + cnt + ", (2)");
        d2.setLineWidth(2.5f);
        d2.setCircleRadius(4.5f);
        d2.setHighLightColor(Color.rgb(244, 117, 117));
        d2.setColor(ColorTemplate.VORDIPLOM_COLORS[0]);
        d2.setCircleColor(ColorTemplate.VORDIPLOM_COLORS[0]);
        d2.setDrawValues(false);

        ArrayList<ILineDataSet> sets = new ArrayList<>();
        sets.add(d1);
        sets.add(d2);

        return new LineData(sets);
    }

    /**
     * generates a random ChartData object with just one DataSet
     *
     * @return Bar data
     */
    private BarData generateDataBar(int cnt) {

        ArrayList<BarEntry> entries = new ArrayList<>();

        for (int i = 0; i < 12; i++) {
            entries.add(new BarEntry(i, (int) (Math.random() * 70) + 30));
        }

        BarDataSet d = new BarDataSet(entries, "New DataSet " + cnt);
        d.setColors(ColorTemplate.VORDIPLOM_COLORS);
        d.setHighLightAlpha(255);

        BarData cd = new BarData(d);
        cd.setBarWidth(0.9f);
        return cd;
    }

    /**
     * generates a random ChartData object with just one DataSet
     *
     * @return Pie data
     */
    private PieData generateDataPie() {

        ArrayList<PieEntry> entries = new ArrayList<>();

        for (int i = 0; i < 4; i++) {
            entries.add(new PieEntry((float) ((Math.random() * 70) + 30), "Quarter " + (i + 1)));
        }

        PieDataSet d = new PieDataSet(entries, "");

        // space between slices
        d.setSliceSpace(2f);
        d.setColors(ColorTemplate.VORDIPLOM_COLORS);

        return new PieData(d);
    }







    @Override
    public void onClick(View v)
    {
        Intent intent = new Intent();
        switch (v.getId())
        {
            case R.id.image_btn_daunxinqunfa:
                intent.setClass(getActivity(),MsgMobanActivity.class);
                startActivity(intent);break;
                //教程
            case R.id.image_btn_jiaochen:
                Toast.makeText(getActivity(),"a",Toast.LENGTH_SHORT).show();
            //  startActivity(intent);break;

            case R.id.image_btn_mobandown:
                intent.setClass(getActivity(),MobanActivity.class);
                startActivity(intent);break;

                //通讯
            case R.id.image_btn_tongxun:
                {
                    intent.setClass(getActivity(), ToFileActivity.class);
                    startActivityForResult(intent, 3);
                //                intent.setClass(getActivity(),ToFileActivity.class);
//                Handler handler=new Handler();
//                //在run里面写了跳转activity
//                Runnable runnable=new Runnable() {
//                    @Override
//                    public void run() {
//
//
//                    }
//                };
//                handler.post(runnable);
//                dialog=ProgressDialog.show(getActivity(),"请稍等","正在打开本地Excel",true,true);
                break;
             }




        }

    }

    /**
     * 跳转到下一个是Hider返回传递的数据
     */
    public static void closeProgressDialog() {

        dialog.dismiss();
    }
    /***
     * 当即将销毁时 isRunning = false;
     */

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        isRunning = false;
    }

    /**
     * ID初始化+事件监听
     */
    private void initViews()
    {

        img_btn_tonxun=view.findViewById(R.id.image_btn_tongxun);
        img_btn_dwlo=view.findViewById(R.id.image_btn_mobandown);
        img_btn_daunxin=view.findViewById(R.id.image_btn_daunxinqunfa);
        img_btn_jiaochen=view.findViewById(R.id.image_btn_jiaochen);

        img_btn_jiaochen.setOnClickListener(this);
        img_btn_daunxin.setOnClickListener(this);
        img_btn_dwlo.setOnClickListener(this);
        img_btn_tonxun.setOnClickListener(this);

        viewPager = (ViewPager) view.findViewById(R.id.viewpager);

//        mIndicatorCircleLine = view.findViewById(R.id.indicator_circle_line);
//       mIndicatorCircleLine.setViewPager(viewPager,5);

        mIndicatorSpring = view.findViewById(R.id.indicator_spring);
        mIndicatorSpring.setViewPager(viewPager,5);

        viewPager.setOnPageChangeListener(this);// 设置页面更新监听

    }

    /**
     * 初始化要显示的数据
     */
    private void initData()
    {

            imageResIds = new int[]{R.drawable.img01, R.drawable.img02, R.drawable.img03, R.drawable.img04, R.drawable.img05};
        /**
         *  初始化要展示的5个ImageView
         */
        imageViewList = new ArrayList<ImageView>();
        ImageView imageView;

        for (int i = 0; i < imageResIds.length; i++)
        {
            // 初始化要显示的图片对象
            imageView = new ImageView(getActivity());

                  Glide.with(getActivity()).load(imageResIds[i])
                    .transform(new GlideRectRound(getActivity(),5)).into(imageView);

               imageViewList.add(imageView);
        }
    }



    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//        tvX.setText(String.valueOf(seekBarX.getProgress()));
//        tvY.setText(String.valueOf(seekBarY.getProgress()));
//
//        setData(seekBarX.getProgress(), seekBarY.getProgress());

        // redraw
       // chart.invalidate();
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {

    }

    @Override
    public void onNothingSelected() {

    }


    /**
     * Vipager
     */
    class MyAdapter extends PagerAdapter
    {

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }


        @Override
        public boolean isViewFromObject(View view, Object object)
        {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position)
        {
            System.out.println("instantiateItem初始化: " + position);
            int newPosition = position % imageViewList.size();

            ImageView imageView = imageViewList.get(newPosition);
            container.addView(imageView);
            return imageView; // 必须重写, 否则报异常
        }

        // 2. 销毁条目
        @Override
        public void destroyItem(ViewGroup container, int position, Object object)
        {
            // object 要销毁的对象
            System.out.println("destroyItem销毁: " + position);
            container.removeView((View) object);
        }
    }

    public void onPageScrolled(int position, float positionOffset,
                               int positionOffsetPixels) {
    }

    public void onPageSelected(int position)
    {
        System.out.println("onPageSelected: " + position);
        int newPosition = position % imageViewList.size();
    }

    public void onPageScrollStateChanged(int state) {
        // 滚动状态变化时调用
    }


}

